package com.sparrow.mvc.ui;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

@SuppressWarnings("serial")
public abstract class JWebBodyControl extends JWebControl {
	/**
	 * 
	 */
	@Override
	public int doEndTag() throws JspException {
		if (this.getVisible() != "false") {
			try {
				this.pageContext.getOut().print("</" + this.getTagName() + ">");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return super.doEndTag();
	}

	public abstract String setTagNameAndGetTagAttributes();

	@Override
	public int doStartTag() throws JspException {
		int returnValue = TagSupport.SKIP_BODY;
		if (!this.getVisible().toLowerCase().equals("false")) {
			StringBuffer writeHTML = new StringBuffer();
			String tagAttributes = this.setTagNameAndGetTagAttributes();
			writeHTML.append(String.format("<%1$s id=\"%2$s\"", this
					.getTagName(), this.getId()));
			writeHTML.append(tagAttributes);
			writeHTML.append(this.getName());
			writeHTML.append(this.getCssClass());
			writeHTML.append(this.getCssText());
			writeHTML.append(this.getTitle());
			writeHTML.append(this.getEvents());
			writeHTML.append(">");

			Object innerHTML = this.pageContext.getRequest().getAttribute(
					this.getId() + ".innerHTML");
			if (innerHTML == null) {
				innerHTML = this.pageContext.getRequest().getAttribute(
						this.getId() + ".value");
			}
			if (innerHTML == null) {
				innerHTML =super.getRequestValue(innerHTML);
			}
			if (innerHTML == null) {
				returnValue = TagSupport.EVAL_BODY_INCLUDE;
			} else {
				writeHTML.append(innerHTML);
			}
			try {
				this.pageContext.getOut().print(writeHTML.toString().trim());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return returnValue;
	}
}
